/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.dao.impl;

import vip.dexian.admin.dao.DepartmentDao;
import vip.dexian.admin.entity.Department;
import vip.dexian.common.CommonAttributes;
import vip.dexian.common.query.Filter;
import vip.dexian.common.query.Listable;
import vip.dexian.common.query.Order;
import vip.dexian.common.utils.FilterUtils;
import vip.dexian.common.utils.OrderUtils;
import vip.dexian.core.base.bean.TreeEntity;
import vip.dexian.core.base.dao.BaseDaoImpl;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 部门
 *
 * @author 挺好的 2023年05月31日 13:55
 */
@Repository ("departmentDaoImpl")
public class DepartmentDaoImpl extends BaseDaoImpl <Department, Long> implements DepartmentDao {

    /**
     * 查找全部部门，将会根据上下级关系自动排序
     *
     * @return {@link vip.dexian.admin.entity.Department}
     */
    @Override
    public List <Department> findAll () {

        List <Order> orders = OrderUtils.builder().asc("grade").asc("order").build();

        Listable listable = Listable.builder().orders(orders).build();

        List <Department> departments = super.findList(listable);

        TreeEntity.sort(departments);

        return departments;
    }

    /**
     * 根据parentId查找子部门，采用递归的方式（主要使用treePath）
     *
     * @param parentId
     *         上级部门id
     *
     * @return {@link vip.dexian.admin.entity.Department} 列表
     */
    @Override
    public List <Department> findChildren (Long parentId) {

        List <Filter> filters = FilterUtils.builder()
                .like("treePath", CommonAttributes.SEPARATOR + parentId + CommonAttributes.SEPARATOR).build();

        Listable listable = Listable.builder().filters(filters).build();

        List <Department> departments = super.findList(listable);

        return departments;
    }

    /**
     * 是否包含子部门
     *
     * @param id
     *         部门id
     *
     * @return 指定的部门如果包含子部门，则返回true，否则返回false
     */
    @Override
    public boolean hasChildren (Long id) {
        List <Filter> filters = FilterUtils.builder().equals("parent.id", id).build();
        return this.exists(filters);
    }
}
